<template>
    <div class="condition-statistic">
        <search-condition @resert="resert" @search="search" :isShowMoreSeach="true" @collapse="collapse"> </search-condition>
        <div class="anotherStatistics anotherStatistic">
            <div class="anotherTop">
                <div style="margin-bottom: 10px" v-if="realTimeData.length != 0">
                    <text class="titleBar">日统计看板</text>
                    <text style="margin: 0 15px; color: #c5d8ff; font-size: 14px">检测设备状态</text>
                    <span v-if="realTimeData[0].isOnline == false">
                        <i style="color: #ff4d4f; font-size: 14px" class="iconfont icon-qishengjigou-zhengchang"></i>
                        <text style="margin-left: 8px; color: #ff4d4f">离线</text>
                    </span>
                    <span v-else>
                        <i style="color: #c5d8ff; font-size: 14px" class="iconfont icon-qishengjigou-zhengchang"></i>
                        <text style="margin-left: 8px; color: #c5d8ff">在线</text>
                    </span>
                </div>
                <text class="explain" v-loading="runningTimeLoading" element-loading-background="#163C54"
                    >累计运行时长：{{ deviceData.cumulativeUmulativeuntimeDuration }}h；累计带载静置时长：{{ deviceData.cumulativeLoadedRest }}h；累计停机时长：{{
                        deviceData.cumulativeStoppage
                    }}h</text
                >
            </div>
            <div class="heating">
                <div class="crane">
                    <text class="specification">实时数据</text>
                    <el-table
                        :data="realTimeData"
                        v-loading="realTimeLoading"
                        element-loading-background="#163C54"
                        :header-cell-style="tableHeaderClassName"
                        :row-style="tableRowClassName"
                        style="width: 100%; color: #bfbfbf; height: 250px; min-height: 313px"
                    >
                        <el-table-column prop="institution" label="机构" />
                        <el-table-column prop="position" label="位置（m）" />
                        <el-table-column prop="speed" label="速度（%）" />
                        <el-table-column prop="load" label="载荷（t）" />
                    </el-table>
                </div>
                <div class="dolly">
                    <text class="specification">统计数据</text>
                    <el-table
                        :data="grandTotalData"
                        v-loading="grandTotalLoading"
                        element-loading-background="#163C54"
                        :header-cell-style="tableHeaderClassName"
                        :row-style="tableRowClassName"
                        style="width: 100%; color: #bfbfbf; height: 250px; min-height: 313px"
                    >
                        <el-table-column prop="evaluateObject" label="机构" />
                        <el-table-column label="带载运行">
                            <el-table-column prop="number" label="次数" />
                            <el-table-column prop="duration" label="时长(h)" />
                            <el-table-column prop="maxSpeed" label="最大速度(%)" />
                        </el-table-column>
                        <el-table-column label="空载运行">
                            <el-table-column prop="plcCumulativeDataRespidles.number" label="次数" />
                            <el-table-column prop="plcCumulativeDataRespidles.duration" label="时长(h)" />
                            <el-table-column prop="plcCumulativeDataRespidles.maxSpeed" label="最大速度(%)" />
                        </el-table-column>
                        <el-table-column label="载荷">
                            <el-table-column prop="maxLoad" label="最大载荷(t)" />
                            <el-table-column prop="cumulativeLoad" label="累计载荷(t)" />
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <div class="anotherStatistics" :style="{ height: height + 'px' }">
            <text class="titleBar">当月热力图</text>
            <div class="heating">
                <div v-if="craneHeatingDataOne.heatMapDataY == ''" class="noCrane">
                    <text>暂无数据</text>
                </div>
                <div v-else class="crane" v-loading="craneLoading" element-loading-background="#163C54">
                    <text class="specification">{{ craneHeatingDataOne.positionName }}</text>
                    <div class="calendar">
                        <canvas id="myCanvas1" style="width: 100%; height: 100%"></canvas>
                    </div>
                    <div class="depth">
                        <text v-for="(item, index) in displayedArray" :key="index">{{ item }}</text>
                    </div>
                    <div class="headEnd">
                        <text>南</text>
                        <text>北</text>
                    </div>
                </div>
                <div class="dolly">
                    <text class="specification">小车位置分布</text>
                    <text class="dollyplace">{{ craneHeatingDataTwo.positionName }}</text>
                    <div v-if="craneHeatingDataTwo.heatMapDataY == ''" class="noHeating">
                        <text>暂无数据</text>
                    </div>
                    <div v-else v-loading="upLoading" element-loading-background="#163C54">
                        <div class="upTrolley">
                            <canvas id="myCanvas2" style="width: 100%; height: 100%"></canvas>
                        </div>
                        <div class="location">
                            <text v-for="item in craneHeatingDataTwo.heatMapDataX" v-show="item % 10 === 0">{{ item }}</text>
                        </div>
                        <div class="describe">
                            <text>司机室侧</text>
                        </div>
                    </div>
                    <text class="dollyplace">{{ craneHeatingDataThr.positionName }}</text>
                    <div v-if="craneHeatingDataThr.heatMapDataY == ''" class="noHeating">
                        <text>暂无数据</text>
                    </div>
                    <div v-else v-loading="downLoading" element-loading-background="#163C54">
                        <div class="upTrolley">
                            <canvas id="myCanvas3" style="width: 100%; height: 100%"></canvas>
                        </div>
                        <div class="location">
                            <text v-for="item in craneHeatingDataThr.heatMapDataX" v-show="item % 10 === 0">{{ item }}</text>
                        </div>
                        <div class="describe">
                            <text>司机室侧</text>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, provide, watch, onMounted, onBeforeUnmount, computed, nextTick } from "vue";
import searchCondition from "@/components/searchCondition.vue";
import { getequipmentarealocationlist } from "@/service/api/equipmentManagement.js";
import { getbasicsequipmentcodelist } from "@/service/api/healthAssessment.js";
import { getDevicestatus, getGrandTotal, getRealTime, getCraneHeating } from "@/service/api/conditionStatistic.js";
import { getbasicsequipmentnamelist } from "@/service/api/faultDetection.js";
import { formConfig, colors } from "./config";
import { getDate } from "@/utils/tiemChange.js";
import { useRoute } from "vue-router";
import emitter from "@/bus/index.js";
import dayjs from "dayjs";
// import Socket from "@/webSocket";

// const socket = new Socket();
const route = useRoute();
const craneLoading = ref(true);
const upLoading = ref(true);
const downLoading = ref(true);
const grandTotalLoading = ref(true);
const realTimeLoading = ref(true);
const runningTimeLoading = ref(true);
const deviceData = ref({});
const deviceFormData = reactive({
    equipmentCode: "",
    ts: ""
});
const grandTotalData = ref();
const realTimeData = ref([]);
const craneHeatingDataOne = ref({});
const craneHeatingDataTwo = ref({});
const craneHeatingDataThr = ref({});
const grandTotalFormData = reactive({
    equipmentCode: "",
    ts: ""
});
const spectrogramData = reactive({
    equipmentCode: "",
    positionValue: "",
    ts: ""
});
// const toDay = ref(new Date());
// const toDayCharacter =
//     toDay.value.getFullYear() +
//     "-" +
//     (toDay.value.getMonth() + 1 < 10 ? "0" + (toDay.value.getMonth() + 1) : toDay.value.getMonth() + 1) +
//     "-" +
//     (toDay.value.getDate() < 10 ? "0" + toDay.value.getDate() : toDay.value.getDate());
// const certainTime = ref(toDayCharacter);
const formData = reactive({ location: "", equipmentCode: "", equipmentTime: getDate(0) });
const height = ref();
const time = ref();

// socket.connect(`/houduanToQianduan/workingConditions/${formData.equipmentCode}`, (res) => {
//     realTimeData.value = res.noticeInfo;
// });
onMounted(() => {
    height.value =
        document.querySelector("body").clientHeight -
        document.querySelector(".header").clientHeight -
        document.querySelector(".search-condition").clientHeight -
        document.querySelector(".anotherStatistic").clientHeight -
        80;
    time.value = setInterval(() => {
        if (formData.equipmentTime != "" && formData.equipmentTime != null && formData.equipmentTime != undefined) {
            grandTotalFormData.ts = formData.equipmentTime + " " + dayjs().format("YYYY-MM-DD HH:mm:ss").slice(-8);
            getRealTime(grandTotalFormData).then((res) => {
                realTimeLoading.value = false;
                if (res.code === 200) {
                    realTimeData.value = res.data;
                }
            });
        }
    }, 3000);
    createPalette;
});
const dynamicArray = ref([]); // 动态数组数据
const displayedArray = computed(() => {
    if (dynamicArray.value.length <= 11) {
        return dynamicArray.value; // 数组长度小于等于9时直接返回全部元素
    } else {
        const step = Math.floor(dynamicArray.value.length / 9); // 计算步长
        let selectedIndexes = [0]; // 首先选中第一个数据点
        for (let i = 1; i <= 9; i++) {
            selectedIndexes.push(i * step);
        }
        selectedIndexes.push(dynamicArray.value.length - 1); // 最后选中最后一个数据点
        return selectedIndexes.map((index) => dynamicArray.value[index]);
    }
});
onBeforeUnmount(() => {
    clearTimeout(time.value);
});

//设备
watch(
    () => formData.location,
    (news) => {
        formData.equipmentCode = "";
        getbasicsequipmentcodelist({ area: news }).then((res) => {
            if (res.code === 200) {
                formConfig.value[1].options = res.data.map((item) => ({ label: item.name, value: item.value }));
            }
        });
        getbasicsequipmentnamelist({ area: news }).then((res) => {
            if (res.code === 200) {
                formConfig.value[2].options = res.data.map((item) => ({ label: item.name, value: item.value }));
            }
        });
    }
);
if (route.query.areaLocation && route.query.code) {
    formData.location = parseInt(route.query.areaLocation);
    getequipmentarealocationlist().then((res) => {
        if (res.code === 200) {
            formConfig.value[0].options = res.data.map((item) => ({ label: item.name, value: parseInt(item.value) }));
        }
    });
    getbasicsequipmentcodelist({ area: route.query.areaLocation }).then((res) => {
        if (res.code === 200) {
            formConfig.value[1].options = res.data.map((item) => ({ label: item.name, value: item.value }));
            formData.equipmentCode = route.query.code;
        }
        statisticTable();
        createPalette();
        upDolly();
        downDolly();
    });
    getbasicsequipmentnamelist({ area: formData.location }).then((res) => {
        if (res.code === 200) {
            formConfig.value[2].options = res.data.map((item) => ({ label: item.name, value: item.value }));
        }
    });
} else {
    getequipmentarealocationlist().then((res) => {
        if (res.code === 200) {
            formConfig.value[0].options = res.data.map((item) => ({ label: item.name, value: item.value }));
            formData.location = formConfig.value[0].options[0].value;
            getbasicsequipmentcodelist({ area: formData.location }).then((res) => {
                if (res.code === 200) {
                    formConfig.value[1].options = res.data.map((item) => ({ label: item.name, value: item.value }));
                    formData.equipmentCode = formConfig.value[1].options[0]?.value;
                    statisticTable();
                    createPalette();
                    upDolly();
                    downDolly();
                }
            });
            getbasicsequipmentnamelist({ area: formData.location }).then((res) => {
                if (res.code === 200) {
                    formConfig.value[2].options = res.data.map((item) => ({ label: item.name, value: item.value }));
                }
            });
        }
    });
}

function statisticTable() {
    console.log(formData);
    deviceFormData.ts = formData.equipmentTime + " 00:00:00";
    if (formData.equipmentCode) {
        deviceFormData.equipmentCode = formData.equipmentCode;
        grandTotalFormData.equipmentCode = formData.equipmentCode;
    }
    //日统计看板时间
    getDevicestatus(deviceFormData).then((res) => {
        runningTimeLoading.value = false;
        if (res.code === 200) {
            deviceData.value = res.data;
        }
    });

    //日统计看板累计表格
    getGrandTotal(deviceFormData).then((res) => {
        grandTotalLoading.value = false;
        if (res.code === 200) {
            grandTotalData.value = res.data;
        }
    });

    //日统计看板实时表格
    getRealTime(grandTotalFormData).then((res) => {
        realTimeLoading.value = false;
        if (res.code === 200) {
            realTimeData.value = res.data;
        }
    });
}

function compare(value) {
    const index = Math.floor(value * 100);
    return colors[index];
}

async function createPalette() {
    // 清除画布
    let canvas = document.getElementById("myCanvas1");
    if (canvas != null && canvas != "" && canvas != undefined) {
        canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
    }
    spectrogramData.equipmentCode = formData.equipmentCode;
    spectrogramData.ts = formData.equipmentTime + " 00:00:00";
    spectrogramData.positionValue = 1;
    const res = await getCraneHeating(spectrogramData);
    craneLoading.value = false;
    if (res.code === 200) {
        craneHeatingDataOne.value = res.data;
        dynamicArray.value = res.data.heatMapDataX;
        nextTick(() => {
            canvas = document.getElementById("myCanvas1");
            if (canvas != null && canvas != "" && canvas != undefined) {
                const width = 300,
                    height = 150;
                let ctx = canvas.getContext("2d");
                let linearGradient = ctx.createLinearGradient(0, 0, 300, 0); // 设置渐变
                const colorValue = new Array(craneHeatingDataOne.value.heatMapDataY.length).fill(null).map((_, index) => (index + 1) / (craneHeatingDataOne.value.heatMapDataY.length + 1));
                for (let index = 0; index < craneHeatingDataOne.value.heatMapDataY.length; index++) {
                    const elementColor = compare(craneHeatingDataOne.value.heatMapDataY[index]);
                    linearGradient.addColorStop(colorValue[index], elementColor);
                }
                ctx.fillStyle = linearGradient; // 填充色
                ctx.fillRect(0, 0, width, height); // (x,y,width,height) 矩形坐标和宽高
            }
        });
    }
}
async function upDolly() {
    // 清除画布
    let canvas = document.getElementById("myCanvas2");
    if (canvas != null && canvas != "" && canvas != undefined) {
        canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
    }
    // 获取数据
    spectrogramData.equipmentCode = formData.equipmentCode;
    spectrogramData.ts = formData.equipmentTime + " 00:00:00";
    spectrogramData.positionValue = 2;
    const res = await getCraneHeating(spectrogramData);
    upLoading.value = false;
    // 绘制热力图
    if (res.code === 200) {
        craneHeatingDataTwo.value = res.data;
        nextTick(() => {
            canvas = document.getElementById("myCanvas2");
            if (canvas != null && canvas != "" && canvas != undefined) {
                const width = 300,
                    height = 150;
                let ctx = canvas.getContext("2d");
                let linearGradient = ctx.createLinearGradient(0, 0, 300, 0); // 设置渐变
                const colorValue = new Array(craneHeatingDataTwo.value.heatMapDataY.length).fill(null).map((_, index) => (index + 1) / (craneHeatingDataTwo.value.heatMapDataY.length + 1));
                for (let index = 0; index < craneHeatingDataTwo.value.heatMapDataY.length; index++) {
                    const elementColor = compare(craneHeatingDataTwo.value.heatMapDataY[index]);
                    linearGradient.addColorStop(colorValue[index], elementColor);
                }
                ctx.fillStyle = linearGradient; // 填充色
                ctx.fillRect(0, 0, width, height); // (x,y,width,height) 矩形坐标和宽高
            }
        });
    }
}
async function downDolly() {
    // 清除画布
    let canvas = document.getElementById("myCanvas3");
    if (canvas != null && canvas != "" && canvas != undefined) {
        canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
    }
    // 获取数据
    spectrogramData.equipmentCode = formData.equipmentCode;
    spectrogramData.ts = formData.equipmentTime + " 00:00:00";
    spectrogramData.positionValue = 3;
    const res = await getCraneHeating(spectrogramData);
    downLoading.value = false;
    // 绘制热力图
    if (res.code === 200) {
        craneHeatingDataThr.value = res.data;
        nextTick(() => {
            canvas = document.getElementById("myCanvas3");
            if (canvas != null && canvas != "" && canvas != undefined) {
                const width = 300,
                    height = 150;
                let ctx = canvas.getContext("2d");
                let linearGradient = ctx.createLinearGradient(0, 0, 300, 0); // 设置渐变
                const colorValue = new Array(craneHeatingDataThr.value.heatMapDataY.length).fill(null).map((_, index) => (index + 1) / (craneHeatingDataThr.value.heatMapDataY.length + 1));
                for (let index = 0; index < craneHeatingDataThr.value.heatMapDataY.length; index++) {
                    const elementColor = compare(craneHeatingDataThr.value.heatMapDataY[index]);
                    linearGradient.addColorStop(colorValue[index], elementColor);
                }
                ctx.fillStyle = linearGradient; // 填充色
                ctx.fillRect(0, 0, width, height); // (x,y,width,height) 矩形坐标和宽高
            }
        });
    }
}

//表格样式
const tableRowClassName = ({ row, rowIndex }) => {
    let styleRow = {};
    if (rowIndex % 2 == 0) {
        styleRow.background = "#0e2b3d";
        return styleRow;
    } else {
        styleRow.background = "#163c54";
        return styleRow;
    }
};
const tableHeaderClassName = ({ row, column, rowIndex, columnIndex }) => {
    if (rowIndex === 0) {
        let styleHeader = {};
        styleHeader.background = "#163c54";
        styleHeader.color = "#BFBFBF";
        return styleHeader;
    }
};

const search = () => {
    if (formData.equipmentCode == "" || formData.equipmentTime == "") {
        ElMessage({
            message: "请选择设备以及日期再进行查询",
            type: "warning"
        });
        return;
    }
    statisticTable();
    createPalette();
    upDolly();
    downDolly();
};
const resert = () => {
    Object.keys(formData).forEach((key) => (formData[key] = ""));
};
const collapse = (isCollapse) => {
    emitter.emit("collapse", isCollapse);
};
// onUnmounted(() => {
//     socket.disconnect();
// });

provide("formData", formData);
provide("formConfig", formConfig);
</script>

<style lang="less" scoped>
.condition-statistic {
    :deep(.el-input__inner) {
        width: 194px;
    }
    :deep(.el-input__wrapper) {
        width: 100%;
    }
    .anotherStatistics {
        box-sizing: border-box;
        padding: 1.25rem;
        background-color: #0e2b3d;
        margin-top: 12px;
        .anotherTop {
            display: flex;
            justify-content: space-between;
            .explain {
                color: #ffffff;
                font-size: 16px;
                font-weight: 500;
            }
        }
        .titleBar {
            font-size: 16px;
            font-weight: 600;
            color: #ffffff;
        }
        :deep(.el-table) {
            --el-table-border-color: auto !important;
        }
        :deep(.el-table thead.is-group th.el-table__cell) {
            background: #163c54;
            color: #bfbfbf;
        }
        :deep(.el-table .cell) {
            text-align: center;
            padding: 0px 1px;
        }
        :deep(.el-table thead) {
            height: 78px;
        }
    }
    .heating {
        font-size: 14px;
        color: #595959;
        display: flex;
        width: 100%;
        ::-webkit-scrollbar {
            width: 3px;
            background-color: #8c8c8c;
        }
        :deep(.el-table) {
            margin-top: 10px;
        }
        .noCrane {
            height: 200px;
            width: 30%;
            background: #163c54;
            color: #c5d8ff;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .crane {
            width: 30%;
            .specification {
                line-height: 20px;
                color: #c5d8ff;
            }
            .calendar {
                margin: 8px 0;
                height: 160px;
            }
            .depth {
                display: flex;
                justify-content: space-between;
                color: #bfbfbf;
            }
            .headEnd {
                display: flex;
                justify-content: space-between;
                margin-top: 5px;
                color: #8c8c8c;
            }
        }
        .dolly {
            width: 68%;
            margin-left: 2%;
            .specification {
                line-height: 20px;
                color: #c5d8ff;
            }
            .dollyplace {
                line-height: 20px;
                display: block;
                margin: 8px 0;
                color: #c5d8ff;
            }
            .noHeating {
                height: 40px;
                width: 100%;
                background: #163c54;
                color: #c5d8ff;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .upTrolley {
                height: 40px;
            }
            .location {
                display: flex;
                justify-content: space-between;
                margin-top: 8px;
                color: #bfbfbf;
            }
            .describe {
                color: #bfbfbf;
            }
        }
    }
    :deep(.el-scrollbar__wrap) {
        background-color: #183c53;
    }
}
</style>
